package action.league;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utility.Pagination;

import com.google.gson.Gson;

import model.dao.LeagueModel;
import model.dto.Country;
import model.dto.League;
import controller.Action;
import controller.ActionForward;

public class ActionListLeague implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		League dto=null;
		LeagueModel dao=new LeagueModel();
		
		
		int page=1;
		int limit=5;
		String search="";
		if(request.getParameter("page")!=null){
			page=Integer.parseInt(request.getParameter("page"));
			System.out.println("Page is NOT null.");
		}else{
			System.out.println("Page is null!!");
		}
		if(request.getParameter("search")!=null){
			search=request.getParameter("search");
		}
		if(request.getParameter("limit")!=null){
			limit=Integer.parseInt(request.getParameter("limit"));
		}
		//Set up pagination
		Pagination pagination=new Pagination();
		pagination.setTotalRecord(dao.count(search));
		pagination.setCurrentPage(page);
		pagination.setLimitRecord(limit);
		
		ArrayList<League> list=new ArrayList<League>();
		ResultSet rs=dao.list(search,pagination.getLimitRecord(), pagination.getCurrentPage());
		while(rs.next()){
			dto=new League();
			dto.setId(rs.getInt("league_id"));
			dto.setName(rs.getString("league_name"));
			dto.setImage(rs.getString("league_image"));
			dto.setCountryId(rs.getInt("country_id"));
			dto.setCountryName(rs.getString("country_name"));
			dto.setCountryImage(rs.getString("country_image"));
			list.add(dto);
		}
		dao.close();
		//Send pagination data
		Hashtable<String, Object> data=new Hashtable<String, Object>();
		data.put("list", list);
		data.put("total_page", pagination.getTotalPage());
		data.put("current_page", pagination.getCurrentPage());
		data.put("has_next_page", pagination.hasNextPage());
		data.put("has_previous_page", pagination.hasPreviousPage());
		data.put("previous_page", pagination.getPreviousPage());
		data.put("next_page", pagination.getNextPage());
		
		String json=new Gson().toJson(data);
		System.out.println(json);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);		
		return null;
	}

}
